#include "Timer.h"
#include <iostream>
Timer::Timer(){
	m_ptimer = new osg::Timer();
	m_ptimer->setStartTick(m_ptimer->tick());
	m_bstart = true;
	m_bpause = false;
	timeLeftTxt = new osgText::Text;
	timeDisplayed[0] = ' ';
	timeDisplayed[1] = ' ';
	timeDisplayed[2] = ':';
	timeDisplayed[3] = ' ';
	timeDisplayed[4] = ' ';
	timeDisplayed[5] = '\0';
	timeLeftTxt->setPosition(osg::Vec3(700.0f,910.,0.0f));
	timeLeftTxt->setCharacterSize(70);
}
void Timer::start(){
	hud = StageManager::getInstance().getCurrentStage()->getHud();	
	m_ptimer->setStartTick(m_ptimer->tick());
	m_bstart = true;
	hud->getGeode()->addDrawable(timeLeftTxt);
}

void Timer::update(){
	// Texte: time left
	int timeLeft = getTimeLeft();
	if(timeLeft>=0){
		// A recurrent bug we couldn't solve come from this code
		/*int mn = int(timeLeft)/60;
		int sec = timeLeft - (mn*60);
		timeDisplayed[0] = char(mn/10+48);
		timeDisplayed[1] = char(mn%10+48);
		timeDisplayed[3] = char(sec/10+48);
		timeDisplayed[4] = char(sec%10+48);
		
		timeLeftTxt->setText(timeDisplayed);*/
	}else{
		hud->endGame("YOU LOOSE! 10m elapsed!");
	}
}
bool Timer::isPause(){
	return m_bpause;
}
bool Timer::isRunning(){
	return m_bstart;
}
void Timer::pause(){
	if(m_bstart){
		if(m_bpause == false){
			m_tstartPause = m_ptimer->tick();
			m_bpause = true;
		}
		else{
			double elapsedTimePause = m_ptimer->delta_s(m_tstartPause,m_ptimer->tick());
			m_ptimer->setStartTick(m_ptimer->getStartTick() + elapsedTimePause/(m_ptimer->getSecondsPerTick()));
			m_bpause = false;
		}
	}
}

void Timer::stop(){
		m_bstart = false;
}
double Timer::getTimeLeft(){
	return 10.*60. - (m_ptimer->time_s());
}